const Router = require('koa-router')
import { ObjectID } from 'mongodb'
import { ApiRouterObj, ContextProp, ObjTypes } from '../appTypes'
import { resolveToken } from "../utils/jwtAuth"
import { log } from "../utils/log"
import api from './index'

export const router = new Router()


const makeArr = [
  ...api
] as Array<ApiRouterObj>


const generateRoute = ()=>{
  makeArr.forEach(item=>{
    if(item.methods == "get"){
      if(item.auth){
        router.get(item.url,(ctx:any)=>auth(ctx,item.call,item.isAdmin));
      }else{
        router.get(item.url,item.call);
      }
    }
    if(item.methods == "post"){
      if(item.auth){
        router.post(item.url,(ctx:any)=>auth(ctx,item.call,item.isAdmin));
      }else{
        router.post(item.url,item.call);
      }
    }
    if(item.methods == "delete"){
      if(item.auth){
        router.delete(item.url,(ctx:any)=>auth(ctx,item.call,item.isAdmin));
      }else{
        router.delete(item.url,item.call);
      }
    }
    if(item.methods == "put"){
      if(item.auth){
        router.put(item.url,(ctx:any)=>auth(ctx,item.call,item.isAdmin));
      }else{
        router.put(item.url,item.call);
      }
    }
  })
}
generateRoute();


export default router


const auth = async(ctx:ContextProp,call:(ctx:ContextProp)=>void,isAdmin?:boolean):Promise<any>=>{
  const token = ctx.request.header.authorization
  const requestUrl = ctx.request.url.split("?")[0];
  //校验登录
  log.info("请求的token是:"+token)
  const result:ObjTypes | string = await resolveToken(token)
  log.info("token解析结果是:"+JSON.stringify(result)+requestUrl);
  if(result == 'token不存在'){
    ctx.status = 401;
    ctx.body={
      code:401,
      msg:"token不存在"
    }
    return false;
  }
  if(result == 'token过期'){
    ctx.status = 401;
    ctx.body={
      code:401,
      msg:"token过期"
    }
    return false
  }
  if(result == 'token错误'){
    ctx.status = 401;
    ctx.body={
      code:401,
      msg:"token错误"
    }
    return false
  }
  //通过校验 查询数据库中的用户信息给出具体的信息
  let tokenUser = result as ObjTypes;
  let users;

  if(isAdmin){ //只能是admin 后台用户请求
    users = await ctx.db("system_users").find({_id:new ObjectID(tokenUser.id)}).toArray();
    if(users.length == 0){
      return ctx.error(400,"非法访问_admin");
    }
  } else {
    users = await ctx.db("users").find({ id: tokenUser.id}).project({ password:0}).toArray();
    if(users.length == 0){
      return ctx.error(400,"非法访问_user");
    }
  }
  ctx.user = users[0];
  ctx.user._id = `${ctx.user._id}`
  await call(ctx);
  return true;
}